import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form ,Select, Upload,  Icon, DatePicker, Modal } from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "ID",
        dataIndex: "id",
        fixed: 'left',
        width: 100,
      },      
        {
          title: "筛选菌株编号",
          dataIndex: "sxjj_id",
          fixed: 'left',
          width: 100,
        },
        {
          title: "菌株保藏编号",
          dataIndex: "jzbc_id",
        },
        {
          title: "菌种类别",
          dataIndex: "add_jyjz",
        },
        {
          title: "分离菌株编号",
          dataIndex: "add_separate_num",
        },
        {
          title: "近缘菌株",
          dataIndex: "r_jyjz",
        },
        {
          title: "菌株序列",
          dataIndex: "info_jzxl",
          editable: true
        },
        {
          title: "采集样品编号",
          dataIndex: "Acq_id",
          editable: true
        },
        {
          title: "分离培养基编号",
          dataIndex: "a_flpyjbh",
 
        },
        {
          title: "传代培养基编号",
          dataIndex: "a_cdpyjid",
          editable: true
        },
        {
          title: "筛选菌株图片",
          dataIndex: "sxjj_pic",
          editable: true,
          render: (text, record) => (
            <Form>
              <Button onClick={value => document.getElementById("sxjj_pic" + record.id).click()}>
                <Icon type="upload" /> 上传
              </Button>
              <Input readOnly id={"sxjj_pic" + record.id} type="file" onChange={env => this.selectFile(env, 'sxjj_pic', record.id)} style={{display: 'none'}} />
            </Form>
          )
        },
        {
          title: "培养温度",
          dataIndex: "info_wd",
          editable: true
        },
        {
          title: "培养周期",
          dataIndex: "info_date",
          editable: true
        },
        {
          title: "分离人",
          dataIndex: "info_person",
          editable: true
        },
        {
          title: "分离时间",
          dataIndex: "info_time",
          editable: true
        },
        {
          title: "需氧类型",
          dataIndex: "a_xylx",
          editable: true,
          render: () => (
            <Select
            mode="tags"
            style={{ width: "100%" }}
            tokenSeparators={[","]}
            showArrow={true}
          >
            <Option value="jack">需氧</Option>
            <Option value="lucy">厌氧</Option>
            <Option value="lucyq">其他</Option>
          </Select>
                )
        },
        {
          title: "菌落描述",
          dataIndex: "a_jlms",
          editable: true
        },
        {
          title: "正面颜色",
          dataIndex: "info_zmys",
          editable: true
        },
        {
          title: "反面颜色",
          dataIndex: "info_fmys",
          editable: true
        },
        {
          title: "孢子有无",
          dataIndex: "info_bzyw",
          editable: true
        },
        {
          title: "是否产色素",
          dataIndex: "info_css",
          editable: true
        },
        {
          title: "菌株价值标记",
          dataIndex: "jzjz_tag",
          editable: true
        },
        {
          title: "入库人员姓名",
          dataIndex: "worker",
          editable: true
        },
        {
          title: "备注",
          dataIndex: "remark",
          editable: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            width: 100,
            render: (text, record) =>
              this.state.dataSource.length >= 1 ? (
                <Popconfirm title="确认删除?" onConfirm={() => this.handleDelete(record.id)}>
                  <a>删除</a>
                </Popconfirm>
              ) : null,
          },
      
    ];

    this.state = {
      dataSource: [],
      newData: {},
      count: 0,
      total: 0,
      loading: false,
      pageNum: 1,
      pageSize: 100
    };    

  }

  selectFile = (env, prefix, idx) => {
    let files = env.target.files;
    let filename = files[0].name;
    // document.getElementById(prefix + idx).value = filename;
  }

  handleDelete = id => {
    const dataSource = [...this.state.dataSource];
    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }
    
    const url = global.api.secondarycreeningInfo + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 

  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 1;
    
    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }
    
    const newData = {
      id: initVal,
      add_separate_num: initVal,
      add_time: moment(new Date(), 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm'), 
    }
    this.setState({
      dataSource: [newData, ...dataSource],
      count: count + 1,
      newData: newData
    });

  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
        <Button onClick={this.handleAdd} type="primary" style={{ marginTop: 16,marginLeft:16 }}>
         添加
        </Button>
        <Button disabled={this.state.newData.id == null} type="primary" style={{ marginLeft:16 }}>
         保存
        </Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 3000 }}
        />
      </Content>
    );
  }
}
const SecondaryScreeningInfo = Form.create()(EditableTable);
export default SecondaryScreeningInfo;
